﻿
using Extented.UI.Core.Native;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Markup;

namespace Extended.WPF.Core.Native
{
	[ContentProperty("RenderTree")]
	public class RenderTemplate {
		public static readonly RenderTemplate Default = new RenderTemplate() {
			RenderTree = new RenderTextBlock() { Name = "contentPresenter" },
			Triggers = new RenderTriggersCollection() {
				new RenderBinding() { Property = "Content", TargetProperty = "Text", TargetName = "contentPresenter"}
			}
		};
		public FrameworkRenderElement RenderTree { get; set; }
		public RenderTriggersCollection Triggers { get; set; }
		public RenderTemplate() {
			Triggers = new RenderTriggersCollection();
		}
		public FrameworkRenderElementContext CreateContext(INamescope namescope, IElementHost elementHost, object dataContext) {
			var context = RenderTree.With(x => x.CreateContext(namescope, elementHost));
			context.DataContext = dataContext;
			return context;
		}
		public void InitializeTemplate(FrameworkRenderElementContext context, INamescope namescope, IElementHost elementHost, IPropertyChangedListener listener) {
			var triggers = Triggers;
			List<RenderTriggerContextBase> contexts = new List<RenderTriggerContextBase>(triggers.Count);
			foreach (RenderTriggerBase trigger in triggers) {
				var triggerContext = trigger.CreateContext(namescope, elementHost);
				triggerContext.Attach(namescope, elementHost, listener);
				contexts.Add(triggerContext);
			}
			namescope.Triggers = contexts;
		}
		public void ReleaseTemplate(FrameworkRenderElementContext context, INamescope namescope, IElementHost element) {
			var triggers = namescope.Triggers;
			if (triggers == null)
				return;
			foreach (var trigger in triggers) {
				trigger.Detach();
			}
			namescope.Triggers = null;
		}
	}
}
